"""
保存数据到rec文件
"""

import os
import re
import shutil

rec_dir_path = "S:\epidata\\ccc"

def run_add_rec_data(rec_dir_path):
  rec_file_name = next((f for f in os.listdir(rec_dir_path) if f.lower().endswith(".rec") and not f.lower().endswith(".data.rec")),None)

  def is_chinese(word):
    """中文判断"""
    pattern = re.compile(r'[^\u4e00-\u9fa5]')
    if pattern.search(word):
      return False
    else:
      return True

  # 每行数据长度
  line_max = 78

  # 解析rec文件
  if rec_file_name is not None:
    # 获取rec原文件数据
    rec_ori_file_path = os.path.join(rec_dir_path, rec_file_name)
    rec_file = open(rec_ori_file_path, 'r',encoding="gbk",errors='ignore')  
    all_dict_data = rec_file.readlines()
    
    # 提取rec文件内的字段数据
    data = [] # [{field:字段名,length:数据长度}]
    for line in all_dict_data:
      line = line.replace("\n","")
      line_arr = [i for i in line.split(' ') if i ]
      if line.startswith('#') or line.startswith('_'):
        data_length = int(line_arr[7])
        # print(line)
        if data_length > 0 :
          field_name = line_arr[0][1:]
          if field_name:
            data.append({"field":field_name.lower(),"length":data_length})
    # print(data,"\nlength",len(data))
    # 构建rec的数据
    all_lines = ""
    line = ""
    for d in data:
      field = d["field"]
      # 默认所有数据为1，z1为 目录学习学习
      # TODO 测试数据 start
      getdata = "1"
      if field=="z1":
        getdata = "目录学习学习"
      # elif field=="A1OTHER":
      #   getdata = "2"
      elif field=="date":
        getdata = "2021/01/01"
      else:
        getdata = "1"
      # TODO 测试数据 end
      
      # 判断数据长度
      str_data_length = 0
      for i in getdata:
        if is_chinese(i):
          str_data_length = str_data_length + 2
        else:
          str_data_length = str_data_length + 1
      # 获取定义的长度
      data_length = d["length"]
      # 需要补充的空格长度
      speace_length = data_length - str_data_length
      speace_str = "".join([' ' for _ in range(speace_length)])
      # 完善后的数据
      true_data = speace_str + getdata
      # print(field,true_data)
      
      # 填充到数据行
      line = line + true_data
      # 行的长度判断及回行
      if len(line) >= line_max:
        all_lines += line[:line_max] + "!\n"
        line = line[line_max:]
    
    # 数据最后一行带回车补空行
    all_lines = all_lines + line + "!\n"
    
    #拷贝源文件为data.rec
    save_file_name = rec_file_name.lower().replace(".rec",".data.rec")
    rec_new_path = os.path.join(rec_dir_path, save_file_name)
    shutil.copy2(rec_ori_file_path, rec_new_path)
    # 往data.rec填充数据
    with open(rec_new_path,"a",encoding='gb2312') as fs:
      # fs.write(all_lines)
      fs.write(all_lines)

    print("save data to rec file success!")
  else:
    print("file not fond")
 
if __name__ == '__main__':
  run_add_rec_data(rec_dir_path)